package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/nosch/smtpoll/smtpclient"
)

func main() {
	// 定义命令行参数
	serverHost := flag.String("host", "localhost", "SMTP server host")
	serverPort := flag.Int("port", 25, "SMTP server port")
	useTLS := flag.Bool("tls", false, "Use TLS")
	from := flag.String("from", "sender@example.com", "From address")
	to := flag.String("to", "recipient@example.com", "To address(es), comma separated")
	subject := flag.String("subject", "Test Email", "Email subject")
	bodyFile := flag.String("body", "This is a test email.", "Email body")
	username := flag.String("username", "", "SMTP认证用户名")
	password := flag.String("password", "", "SMTP认证密码")
	heloHost := flag.String("helo", "", "HELO主机名（默认使用服务器主机名）")
	flag.Parse()

	// 验证必需参数
	if *from == "" {
		log.Fatal("发件人邮箱地址不能为空")
	}
	if *to == "" {
		log.Fatal("收件人邮箱地址不能为空")
	}

	// 创建SMTP客户端
	client := smtpclient.NewSMTPClient(*serverHost, *serverPort, *useTLS)

	// 设置认证信息
	if *username != "" && *password != "" {
		client.SetAuth(*username, *password)
	}

	// 设置HELO主机名
	if *heloHost != "" {
		client.SetHeloHost(*heloHost)
	}

	// 连接到服务器
	err := client.Connect()
	if err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	defer client.Close()

	// 读取邮件正文
	var body string
	if *bodyFile != "" {
		content, err := os.ReadFile(*bodyFile)
		if err != nil {
			log.Fatalf("读取邮件正文文件失败: %v", err)
		}
		body = string(content)
	} else {
		// 从标准输入读取
		scanner := bufio.NewScanner(os.Stdin)
		var lines []string
		for scanner.Scan() {
			lines = append(lines, scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			log.Fatalf("读取标准输入失败: %v", err)
		}
		body = strings.Join(lines, "\r\n")
	}

	// 生成邮件内容
	email := smtpclient.GenerateEmail(*from, strings.Split(*to, ","), *subject, body)

	// 发送邮件
	recipients := strings.Split(*to, ",")
	err = client.SendMail(*from, recipients, email)
	if err != nil {
		log.Fatalf("发送邮件失败: %v", err)
	}

	fmt.Println("邮件发送成功！")
}
